//
//  CSSComposeViewController.swift
//  weibo28
//
//  Created by chushushan on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CSSComposeViewController: UIViewController, UITextViewDelegate {

    //懒加载右侧按钮
    private lazy var rightButton: UIButton = {
    
        let button = UIButton()
        
        //点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        //设置背景颜色
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //设置文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        button.frame.size = CGSize(width: 45, height: 30)
        
        return button
    }()
    
    //自定义titleview
    private lazy var titleview: UILabel = {
    
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        
        if let name = CSSUserAccountViewModel.shareUserAccount.userAccount?.name {
        let title: String = "发微博\n\(name)"
        let range = (title as NSString).rangeOfString(name)
            
        //创建父文本对象
        let attributedStr = NSMutableAttributedString(string: title)
        //修改颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            label.attributedText = attributedStr
        
        } else {
        
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()

        return label
    }()
    
    //自定义textView
    private lazy var textView: CSSComposeTextView = {
    
        let view = CSSComposeTextView()
        
        view.delegate = self
        view.font = UIFont.systemFontOfSize(17)
        //垂直方向允许滚动
        view.alwaysBounceVertical = true
        
        return view
        
    }()
    
    //toobar
    private lazy var toolBar: CSSComposeTooBar = {
        
        let view = CSSComposeTooBar(frame: CGRectZero)
        return view
    
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        //监听键盘frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification
            , object: nil)
        
        
        setupUI()
    }

    private func setupUI() {
    
        setupNavUI()
        view.backgroundColor = UIColor.orangeColor()
    
        view.addSubview(textView)
        
        view.addSubview(toolBar)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(44)
        }
        
        
        //toolbar按钮的点击事件
        toolBar.didSeletedButtonClosure = { [weak self] (type: CSSComposeTooBarButtonType) in
            switch type {
            case .Picture:
                print("Picture")
                self?.didSelectedPicture()
                
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
            case .Add:
                print("Add")
            }

        }

    }
    //设置nav
    private func setupNavUI() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleview
    }
    
    // MARK: - 点击事件
    
    //发送按钮点击事件
    @objc private func sendAction() {
        //准备参数
        let accesstoken = CSSUserAccountViewModel.shareUserAccount.accessToken!
        let status = textView.text!
        
        //请求发送微博接口
        SVProgressHUD.show()
        
        CSSNetWorkingTools.sharedTools.updata(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
            SVProgressHUD.showErrorWithStatus("网络请求异常")
                return
                
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            UIView.animateWithDuration(1, animations: { () -> Void in
                self.dismissViewControllerAnimated(true, completion: nil)
            })
        }
        
        
    }
    
    
    // MARK: - 键盘的监听事件
    @objc private func keyboardChageFrame(notif: NSNotification) {
    
//        print(notif.userInfo)
        
        let keyboardFrame = (notif.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
//        print(keyboardFrame)
        let animationDuration = (notif.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
//        print(animationDuration)
        
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.height)
        }
        
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //  MARK:   
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    
    
    
    //nav左侧button点击事件
    @objc private func cancelAction() {
    
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // MARK: - UITextViewDelegate代理
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
    // MARK: - 移除监听
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

    
}



extension CSSComposeViewController: UIImagePickerControllerDelegate {
    
    func didSelectedPicture() {
    
        let pictureVc = UIImagePickerController()
        
         pictureVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            
            pictureVc.sourceType = .Camera
        
        } else {
        
            pictureVc.sourceType = .PhotoLibrary
        }
    
    }



}






